/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisyimport.foxml.images;

import cz.mzk.kramerius.commons.PropertyLoader;
import cz.mzk.kramerius.commons.RandomBasedUuidGenerator;
import cz.mzk.kramerius.commons.UuidGenerator;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Properties;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author Martin Rehanek (rehan@mzk.cz)
 */
public class PreviewGenerator {

    private File pictureDir;
    private final UuidGenerator uuidGenerator;
    private static final Logger logger = Logger.getLogger(PreviewGenerator.class.getName());
    private static final String PROP_PICTURES_DIR = "Convertor.downloadedPicturesDir";
    public static final int previewHightInPixels = 125;

    public PreviewGenerator(Properties properties) {
        //uuidGenerator = EthAddrUuidGenerator.instanceOf(properties);
        uuidGenerator = RandomBasedUuidGenerator.instanceOf();
        PropertyLoader propertyLoader = new PropertyLoader(properties);
        pictureDir = propertyLoader.loadDir(PROP_PICTURES_DIR, true, true, true);
    }

    public File generatePreview(File originalImage) throws IOException {
        File previewFile = buildPreviewFile(originalImage);
        saveIfNotPresent(previewFile, originalImage);
        return previewFile;
    }

    private File buildPreviewFile(File originalImage) {
        String filename = pictureDir.getAbsolutePath()
                + File.separator
                + "preview_"
                + originalImage.getName();
        return new File(filename);
    }

    private void saveIfNotPresent(File previewFile, File originalImage) throws IOException {
        if (previewFile.exists() && previewFile.getTotalSpace() != 0) {
            System.out.println("preview exists: " + previewFile.getAbsolutePath());
        } else {
            byte[] previewData = scaleImage(originalImage, previewHightInPixels);
            saveData(previewData, previewFile);
            System.out.println("generating preview: " + previewFile.getAbsolutePath());
        }
    }

    private void saveData(byte[] data, File file) throws IOException {
        FileOutputStream out = new FileOutputStream(file);
        out.write(data);
        out.flush();
        out.close();
    }

    private File createOutFile() {
        StringBuilder fileName = new StringBuilder();
        fileName.append(pictureDir.getAbsolutePath());
        fileName.append(File.separatorChar);
        fileName.append(uuidGenerator.generateUuid());
        fileName.append(".jpg");
        return new File(fileName.toString());
    }

    private byte[] scaleImage(File originalFile, int height) throws IOException, MalformedURLException {
        Image img = ImageIO.read(originalFile);
        BufferedImage scaledImage = scaleByHeight(KrameriusImageSupport.toBufferedImage(img), height);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(scaledImage, "jpg", outputStream);
        return outputStream.toByteArray();

    }

    private BufferedImage scaleByHeight(BufferedImage img, int height) {
        int nHeight = height;
        ImageObserver observer = new ImageObserver() {
            public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
                return false;
            }
        };
        double div = (double) img.getHeight(observer) / (double) nHeight;
        double nWidth = (double) img.getWidth(observer) / div;
        BufferedImage scaledImage = KrameriusImageSupport.scale(img, (int) nWidth, nHeight);
        return scaledImage;
    }
}
